<script setup lang="ts">
import PointGroupTree from '@/components/symmetry/PointGroupTree.vue'
import LoadingOverlay from '@/components/ui/LoadingOverlay.vue'
import { request } from '@/network/axios'
import type { PointGroupsResponse } from '@/types/symmetry'
import { formatSchoenflies } from '@/utils/formatters'
import { renderInline } from '@/utils/katex'
import { computed } from 'vue'
import { useRequest } from 'vue-hooks-plus'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

const router = useRouter()
const { t } = useI18n()

const { data, loading } = useRequest(() => request<PointGroupsResponse>('/symmetry/point-groups'))

const crystallographicLayout = [
  ['C1', 'C2', 'C3', 'C4', 'C6'],
  ['Cs', 'Ci'],
  ['C2v', 'C3v', 'C4v', 'C6v'],
  ['C2h', 'C3h', 'C4h', 'C6h'],
  ['S4', 'S6'],
  ['D2', 'D3', 'D4', 'D6'],
  ['D2h', 'D3h', 'D4h', 'D6h'],
  ['D2d', 'D3d'],
  ['T', 'Th', 'Td', 'O', 'Oh']
]

const families = ['Cn', 'Cnv', 'Cnh', 'Sn', 'Dn', 'Dnh', 'Dnd', 'I', 'Ih']

const nonCrystalFamilies = computed(() =>
  families.map(family => ({
    family,
    groups: data.value?.data?.filter(g => !g.isCrystallographic).filter(g => g.family === family)
  }))
)
</script>

<template>
  <div class="space-y-8">
    <div class="relative grid grid-cols-2 gap-6">
      <LoadingOverlay v-if="loading" />

      <div class="card bg-base-100 border-base-300 border shadow-md">
        <div class="card-body gap-4">
          <h2 class="card-title">
            <span class="bg-primary h-6 w-2 rounded-full"></span>
            {{ t('views.pointGroups.crystallographicTitle') }}
          </h2>

          <div v-for="(row, idx) in crystallographicLayout" :key="idx" class="flex flex-wrap gap-2">
            <button v-for="symbol in row" :key="symbol" class="btn btn-lg btn-ghost w-20" @click="router.push(`/point-groups/${symbol}`)" v-html="renderInline(formatSchoenflies(symbol))"></button>
          </div>
        </div>
      </div>

      <div class="card bg-base-100 border-base-300 border shadow-md">
        <div class="card-body gap-4">
          <h2 class="card-title">
            <span class="bg-secondary h-6 w-2 rounded-full"></span>
            {{ t('views.pointGroups.nonCrystallographicTitle') }}
          </h2>

          <div v-for="item in nonCrystalFamilies" :key="item.family" class="grid grid-cols-2 gap-4">
            <button v-for="group in item.groups" :key="group.groupId" class="btn btn-lg btn-ghost justify-start" @click="router.push(`/point-groups/${group.groupId}`)">
              <span v-html="renderInline(formatSchoenflies(group.schoenflies))"></span>
              <span v-if="group.parity">({{ group.parity }})</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <PointGroupTree />
  </div>
</template>
